package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dmortime on 12/03/2014.
 */
public class LogInMenu implements IMenu {
    private OutputWriter outputWriter;
    private InputReader inputReader;
    private Library library;
    private List<Customer> knownCustomers;

    public LogInMenu(OutputWriter outputWriter, InputReader inputReader, Library library) {
        this.outputWriter = outputWriter;
        this.inputReader = inputReader;
        this.library = library;
        this.knownCustomers = new ArrayList<Customer>();
        knownCustomers.add(new Customer("111-1111", "password"));
        knownCustomers.add(new Customer("222-2222", "password2"));
    }

    public void display() {

    }

    public IMenu nextMenu() {
        String userId = promptForUserId();

        Customer customer = getCustomerByUserId(userId);
        if(customer == null) return null;

        String password = promptForPassword();

        if(matchesCustomerPassword(customer, password)) {
            outputWriter.writeLines("You are now logged in!");
            // TODO: Need a test to force MainMenuWithLoggedInCustomer to be created with correct customer instance.
            return new MainMenuWithLoggedInCustomer(outputWriter, inputReader, library, new Customer("111-1111", "password"));
        } else {
            outputWriter.writeLines("Your password was incorrect!");
            return new MainMenuWithoutLoggedInCustomer(outputWriter, inputReader, library);
        }
    }

    private Customer getCustomerByUserId(String userId) {
        for (Customer customer : knownCustomers) {
            if(customer.getUserId().equals(userId)) {
                return customer;
            }
        }
        return null;
    }

    private boolean matchesCustomerPassword(Customer customer, String password) {
        return customer.isCorrectPassword(password);
    }

    private String promptForUserId() {
        outputWriter.writeLines("Please enter your library ID:");
        return inputReader.getInput();
    }

    private String promptForPassword() {
        outputWriter.writeLines("Enter your password:");
        return inputReader.getInput();
    }

}
